<template>
  <div>
    <div class="login-container">
      <div class="logo-container clearfix">
        <img src="@/assets/logo.png" alt="">
        <h3 class="title">空间云助手</h3>
      </div>

      <el-row style="margin-top: 100px;position: fixed;bottom: 50px;left: 50%;margin-left: -500px" class="clearfix">
        <el-row class="left-content fl">
          <div class="shade"></div>

          <div class="note">
            <div class="title">空间数字化云运营</div>
            <div>
              用系统进行规范、记录、统计和反馈
            </div>
          </div>
        </el-row>
        <el-row class="r-content fl">
          <div class="title">
            运营商
          </div>
          <!--登陆-->
          <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="off"
                   label-position="left">
            <el-form-item prop="username">
        <span class="svg-container svg-container_login">
          <svg-icon icon-class="user"/>
        </span>
              <el-input v-model.trim="loginForm.username" name="username" clearable type="text" auto-complete="off"
                        placeholder="用户名"/>
            </el-form-item>
            <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password"/>
        </span>
              <el-input
                :type="pwdType"
                v-model="loginForm.password"
                name="password"
                auto-complete="on"
                placeholder="密码"
                @keyup.enter.native="handleLogin"/>
              <span class="show-pwd" @click="showPwd">
          <svg-icon icon-class="eye"/>
        </span>
            </el-form-item>
            <el-form-item>
              <el-button :loading="loading" type="primary" class="login-btn" @click.native.prevent="handleLogin">
                登录
              </el-button>
            </el-form-item>
            <!--<div class="forget-password" @click="()=>{dialogVisible=true;changeStatus(1)}">
              忘记密码？
            </div>-->
          </el-form>
        </el-row>
        <el-row class="footer">
         <div>
           —— 专注空间云运营系统的技术服务商 ——
         </div>

          Copyright © 2020 杭州诗码科技有限公司 All Rights Reserved. 浙ICP备19002089号
        </el-row>
      </el-row>
    </div>

    <!--忘记密码弹窗-->
    <el-dialog
      title="找回密码"
      :visible.sync="dialogVisible"
      width="30%"
      :center="true"
      :before-close="handleClose">
      <!--输入账号-->
      <el-form v-show="pageStatus === 1" ref="accountForm" class="login-form" :model="accountForm" label-width="80px">
        <h3>请输入系统账号</h3>
        <el-form-item prop="username" label="账号：" :rules="[{required:true,message:'请输入账号'}]">
          <el-input
            type="text"
            v-model.trim="accountForm.username"
            name="username"/>
        </el-form-item>
      </el-form>
      <!--手机验证-->
      <el-form v-show="pageStatus === 2" ref="phoneForm" class="login-form" :rules="phoneFormRules" :model="phoneForm"
               label-width="80px">
        <h3>你的系统中录入的手机号尾号为{{phoneForm.endMobile}}</h3>
        <el-form-item prop="mobile" label="手机号：">
          <el-input
            type="number"
            v-model.trim="phoneForm.mobile"
            name="mobile"/>
        </el-form-item>
        <el-form-item prop="code" label="验证码：">
          <el-input
            type="text"
            v-model.trim="phoneForm.code"
            name="code"
            class="messcode-input"/>
          <el-button v-if="!countDown" @click="getMessCode">获取验证码</el-button>
          <el-button v-else type="info">重新获取（{{time}}）</el-button>
        </el-form-item>
      </el-form>
      <!--设置密码-->
      <el-form v-show="pageStatus === 3" ref="passwordForm" class="login-form" :rules="passwordFormRules"
               :model="passwordForm" label-width="110px">
        <h3>请设置新的登录密码</h3>
        <el-form-item prop="newPass" label="新密码：">
          <el-input
            type="text"
            v-model.trim="passwordForm.password"
            name="newPass"/>
        </el-form-item>
        <el-form-item prop="repeatPass" label="确认密码：">
          <el-input
            type="text"
            v-model.trim="passwordForm.confirmPassword"
            name="repeatPass"/>
        </el-form-item>
      </el-form>
      <!--设置成功-->
      <el-form v-show="pageStatus === 4">
        <div class="set-success">
          你已成功设置新的密码，请重新登录
        </div>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button v-if="pageStatus === 1" type="primary" class="next-btn" @click.native.prevent="handleAccount">
          下一步
        </el-button>
        <el-button v-if="pageStatus === 2" type="primary" class="next-btn" @click.native.prevent="handlePhone">
          下一步
        </el-button>
        <el-button v-if="pageStatus === 3" type="primary" class="next-btn" @click.native.prevent="handlePassword">
          下一步
        </el-button>
        <el-button v-if="pageStatus === 4" type="primary" class="next-btn" @click.native.prevent="dialogVisible=false">
          重新登录
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

  import {isvalidUsername} from '@/utils/validate'
  import {constantRouterMap} from '@/router'
  import {mapGetters} from 'vuex'
  //import _getMenuList from '../../permission'
  import {setToken, getToken} from '@/utils/auth'
  import loginApi from '@/api/login'
  import userManage from '@/api/main/account/userManage'
  import {getSysParams} from '@/api/common'

  export default {
    name: 'Login',
    data() {
      const validateUsername = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入用户名'))
        } else {
          callback()
        }
      }
      const validateMessCode = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入短信验证码'))
        } else {
          callback()
        }
      }
      const validatePass = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入密码'))
        } else {
          callback()
        }
      }

      const validateNewPass = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入密码'))
        } else if (this.passwordForm.password.length < 6) {
          callback(new Error('输入的密码不得少于6位'))
        } else {
          callback()
        }
      }
      const validateRepeatPass = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入确认密码'))
        } else if (this.passwordForm.password !== this.passwordForm.confirmPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }
      return {
        loginForm: {
          username: '',
          password: ''
        },
        loginRules: {
          username: [{required: true, trigger: 'blur', validator: validateUsername}],
          password: [{required: true, trigger: 'blur', validator: validatePass}]
        },
        pwdType: 'password',
        loading: false,
        redirect: undefined,
        pageStatus: 1,//1：手机校验；2：重置密码
        dialogVisible: false,
        accountForm: {
          username: ''
        },
        phoneForm: {
          username: '',
          endMobile: '',
          mobile: '',
          code: ''
        },
        phoneFormRules: {
          mobile: [
            {required: true, trigger: 'blur', message: '请输入手机号'},
            {min: 11, max: 11, message: '输入的手机号不正确', trigger: 'blur'}
          ],
          code: [{required: true, trigger: 'blur', validator: validateMessCode}]
        },
        passwordForm: {
          password: '',
          confirmPassword: ''
        },
        passwordFormRules: {
          adminUserId: '',
          password: [{required: true, validator: validateNewPass}],
          confirmPassword: [{required: true, validator: validateRepeatPass}]
        },
        time: 60,
        countDown: false
      }
    },
    watch: {
      $route: {
        handler: function (route) {
          this.redirect = route.query && decodeURIComponent(route.query.redirectUrl)
        },
        immediate: true
      }
    },
    methods: {
      timeCountDown() {
        this.countDown = true
        let timeCountDown = setInterval(() => {
          if (this.time > 0) {
            this.time--
          } else {
            this.countDown = false
            clearInterval(timeCountDown)
          }
        }, 1000)
      },
      getMessCode() {
        loginApi.sendSms(this.phoneForm).then(res => {
          this.handleMessage(res)
          if (res.code === '200') {
            this.timeCountDown()
          }
        })

      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done()
          })
      },
      getSysEnums() {
        getSysParams().then(res => {
          if (res.code === '200') {
            const enums = res.body;
            let data = {
              ossDir: JSON.parse(enums.ossUploadDir.value),
              videoCateId: JSON.parse(enums.vodParams.value)
            }
            this.$store.commit("saveSysEnums", data);
            console.log(this.$store.getters);
          }
        })
      },
      showPwd() {
        if (this.pwdType === 'password') {
          this.pwdType = ''
        } else {
          this.pwdType = 'password'
        }
      },
      changeStatus(status) {
        this.pageStatus = status
      },
      //输入账号
      handleAccount() {
        this.$refs.accountForm.validate(valid => {
          if (valid) {
            this.getUserInfo(this.accountForm.username)
          }
        })
      },
      //短信验证码验证
      verifyCode() {
        let {mobile, code} = this.phoneForm
        loginApi.verifyCode(mobile, code).then(res => {
          if (res.code === '200') {
            this.changeStatus(3)
          } else {
            return this.$message.error(res.message)
          }
        })
      },
      //输入手机号、验证码 下一步
      handlePhone() {
        this.$refs.phoneForm.validate(valid => {
          if (valid) {
            this.verifyCode()
          }
        })
      },
      //重置密码
      resetPassword() {
        loginApi.resetPassword(this.passwordForm).then(res => {
          this.handleMessage(res)
          if (res.code === '200') {
            this.changeStatus(4)
          }
        })
      },
      //重置密码 下一步
      handlePassword() {
        this.$refs.passwordForm.validate(valid => {
          if (valid) {
            this.resetPassword()
          }
        })
      },
      getUserInfo(name) {
        let _this = this
        loginApi.findUserByUsername(this.accountForm.username).then(res => {
          if (res.code === '200') {
            let {mobile, adminUserId, username} = res.body

            _this.phoneForm.endMobile = mobile
            _this.phoneForm.username = username

            _this.passwordForm.adminUserId = adminUserId
            _this.changeStatus(2)
          } else {
            _this.$message.error(res.message)
          }
        })
      },
      handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true
            let {username, password} = this.loginForm
            loginApi.login(username, password).then((res) => {
              if(res.access_token){
                setToken('token-B', res.access_token)
                setToken('tokenType', res.token_type)
                setToken('account-B', username)
                setToken('useId-B', res.userId)

                // this.$router.push({path: '/'})
                // window.location.href = location.protocol
                location.reload()
              }
              this.loading = false
            }).catch((err) => {
              this.loading = false
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    mounted() {
      // lineDraw()
    },
    computed: {
      // ...mapGetters([
      //   'roles'  // 用于表格组件
      // ])
    },
    created() {

    }

  }
</script>

<style rel="stylesheet/scss" lang="scss">
  $bg: #2d3a4b;
  $light_gray: #eee;
  /* reset element-ui css */
  .login-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        padding: 12px 5px 12px 15px;
        border: none;
        border-bottom: 1px solid #ddd;
        border-radius: 0;
        height: 47px;
        &:-webkit-autofill {
          -webkit-box-shadow: 0 0 0px 1000px #fff inset !important;
          -webkit-text-fill-color: #000 !important;
        }
      }
    }

    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      border-radius: 5px;
      color: #454545;
    }

    .el-form-item__error {
      padding-left: 35px;
    }

    .login-btn {
      width: 85%;
      margin-left: 10%;
      height: 55px;
      font-pageSize: 15px;
      border-radius: 70px;
      margin-top: 40px;
    }
  }


</style>

<style rel="stylesheet/scss" lang="scss" scoped>
  $bg: #e0b1af;
  $dark_gray: #889aa4;
  $light_gray: #eee;
  .logo-container {
    margin-top: 20px;
    margin-left: 20px;

    img {
      float: left;
      width: 60px;
      padding: 8px;
      border-radius: 300px;
      background: #fff;
      margin-right: 10px;
    }

    .title {
      float: left;
      font-pageSize: 26px;
      font-weight: 400;
      line-height: 9px;

    }

  }
  .left-content{
    width: 400px;
    height: 500px;
    background: url("~@/assets/login-bg.png");
    position: relative;
    border-radius:15px;
    .shade{
      position: absolute;
      left: 0px;
      top: 0px;
      width: 400px;
      height: 500px;
      background-color: rgba(0, 0, 0, 0.247058823529412);
      z-index: 1;
      border: none;
      border-radius: 15px;
      -moz-box-shadow: none;
      -webkit-box-shadow: none;
      box-shadow: none;
    }
    .note{
      position: relative;
      z-index: 2;
      color: #fff;
      text-align: center;
      padding-top: 100px;
      div{
        font-weight: 500;
        font-pageSize: 16px;
      }
      .title{
        font-pageSize:30px ;
        margin-bottom: 50px;

      }
    }
  }
  .r-content{
    width: 520px;
    height: 500px;
    background: #fff;
    .title{
        margin: 100px;
      margin-left: 80px;
      font-pageSize: 18px;
      font-weight: 400;
    }
  }
  .footer{
    text-align: center;
    font-pageSize: 12px;
    color: #999;
    clear: both;
    width: 1000px;
    div{
      color: #333;
      font-pageSize: 14px;
      margin: 20px;
      margin-top: 80px;
    }
  }

  .forget-password {
    color: #409EFF;
    text-align: center;
    font-pageSize: 14px;
    cursor: pointer;
  }

  .login-container {
    position: fixed;
    height: 100%;
    width: 100%;
    background: rgba(243, 246, 249, 1);

    .login-form {
      position: absolute;
      left: 0;
      right: 0;
      width: 80%;
      bottom: 0;
      max-width: 100%;
      margin: 80px auto;
      background: #fff;
    }

    .tips {
      font-pageSize: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;

      &_login {
        font-pageSize: 20px;
      }
    }


    .show-pwd {
      position: absolute;
      right: 30px;
      top: 7px;
      font-pageSize: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }
  }

  .login-form {
    .el-input {
      width: 85%;
    }

    .messcode-input {
      width: 56%;
    }
  }

  .next-btn {
    width: 70%;
  }

  .set-success {
    text-align: center;
    margin: 60px 0;
  }
</style>
